data_packet <- function(data,proportion=0.8){
  if (!is.data.frame(data)) {
    stop("The 'data' argument must be a data frame.")
  }
  if(!is.double(proportion)){
    stop("The 'proportion' argument must be a double.")
  }
  set.seed(123)
  trainIndex <- createDataPartition(mydata$diagnosis, p = proportion, list = FALSE, times = 1)
  allIndices <- 1:nrow(mydata)
  testDataIndices <- setdiff(allIndices, trainIndex)
  trainData <- mydata[trainIndex, ]
  testData <- mydata[testDataIndices, ]
  write.csv(trainData,file="train.csv")
  write.csv(testData,file="test.csv")
  
  packeted_data <- list("train_data"=trainData,"test_data"=testData)
  return(packeted_data)
}


set_column_factor <- function(data,columns){
  # 检查columns是否为字符向量  
  if (!is.character(columns)) {  
    stop(sprintf("'%s'参数必须是一个字符向量",columns))
  } 
  
  # 遍历列名并转换  
  for (col in columns) {  
    if (col %in% names(data)) {  
      data[[col]] <- as.factor(data[[col]])  
    } else {  
      warning(sprintf("列 '%s' 不存在于数据框中，将被忽略。", col))  
    }  
  }  
  
  return (data)
}


set_column_num <- function(data,columns){
  # 检查columns是否为字符向量  
  if (!is.character(columns)) {  
    stop(sprintf("'%s'参数必须是一个字符向量",columns))
  } 
  # 遍历列名并转换  
  for (col in columns) {  
    if (col %in% names(data)) {  
      data[[col]] <- as.numeric(as.character(data[[col]]))  
    } else {  
      warning(sprintf("列 '%s' 不存在于数据框中，将被忽略。", col))  
    }  
  }  
  
  return (data)
}


dummy_vars <- function(data,column_names){
  if(is.null(data)){
    stop("test or train data frame is null.")
  }
  if(!is.data.frame(data)){
    stop("test or train must be data frame.")
  }
  if(is.null(column_names)  || length(column_names) <= 0){
    stop("column names must not empty.")
  }
  for(name in column_names){
    data[[name]] <- as.factor(data[[name]])
    formula_string <- paste("~", name)
    formula_object <- as.formula(formula_string)
    dummy_model <- dummyVars(formula_object, data = data)
    df_encoded <- predict(dummy_model, newdata = data)
    encoded_data <- as.data.frame(df_encoded)
    remove_data <- data %>% select(-all_of(name))
    data <- bind_cols(remove_data, encoded_data)
  }
  return(data)
}

min_max_scale = function(x){
  value <- (x-min(x))/(max(x)-min(x))
  return(value)
}